package com.example.intercept;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Resource
    private ObjectMapper objectMapper;

    @AfterReturning(value = "within(com.example.controller..*)", returning = "rvt")
    public void after(Object rvt) {
//        log.info("接口返回:{}", JSON.toJSON(rvt));
    }

//    @Before("execution(* com.hw8.controller..*(..))")
    public void before(JoinPoint point) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object[] args = point.getArgs();
        log.info("url={}", request.getRequestURL());
        log.info("请求参数:{}", Arrays.toString(args));
    }

    @Around(value = "execution(* com.example.controller..*(..))")
    public Object assertAround(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
       /* TokenItem tokenItem = JWTUtil.parseToken(token);
        if (tokenItem == null) {
            log.error("没有找到token= {} 对应信息",token);
        }*/
//        request.setAttribute("userId",tokenItem.getUserId());
        request.setAttribute("userId", 299l);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        log.info("uri:{},{},params: {}",uri,method,pjp.getArgs());

        // result的值就是被拦截方法的返回值
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long continueTime = end - start;
//        if(continueTime / 1000 > 0){
//            log.info("接口执行了 {} 毫秒",continueTime);
//        }
        log.info("uri:{},执行了 {} 毫秒",uri,continueTime);
//        log.info("请求结束，controller的返回值是 " + objectMapper.writeValueAsString(result));
        return result;
    }

}
